#include "tcp_server.h"

Tcp_server::Tcp_server()
{

}

Tcp_server::~Tcp_server()
{
    close(sockfd);
}

void Tcp_server::Init(const char* argv[])
{
    struct sockaddr_in serveraddr;
    addrlen = sizeof(struct sockaddr_in);
    memset(&serveraddr, 0, addrlen);
    memset(&clientaddr, 0, addrlen);

    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd == -1)
    {
        ERROR("socket is error");
    }

    serveraddr.sin_family = AF_INET;
    serveraddr.sin_addr.s_addr = inet_addr(argv[2]);
    serveraddr.sin_port = htons(atoi(argv[3]));

    if(bind(sockfd, (struct sockaddr *)&serveraddr, addrlen) == -1)
    {
        ERROR("bind is error");
    }

    if(listen(sockfd, 5) == -1)
    {
        ERROR("listen is error");
    }
}

int Tcp_server::accept_wait_client()
{
        if((acceptfd = accept(sockfd, (struct sockaddr *)&clientaddr, &addrlen)) == -1)
        {
            close(acceptfd);
            Print_RED("accept is error");
            return -1;
        }
        Print_GREEN("Client:[%s][%d] Sink!",inet_ntoa((clientaddr).sin_addr),ntohs((clientaddr).sin_port));
        return 0;
}

void Tcp_server::send_rgb_data(VideoDevice *ptVideoDevice)
{
#ifdef YUYV
    int total_size = ptVideoDevice->iHeight * ptVideoDevice->iWidth * 3;  // 总数据大小
#elif defined(MJPEG)
    int total_size = ptVideoDevice->iVideoBufMaxLen;  // 总数据大小
#else
#endif
    int packet_size = 4096;  // 单个数据包的大小
    int sent_bytes = 0;
    
    while (sent_bytes < total_size) {
        int bytes_to_send = total_size - sent_bytes;

        if(bytes_to_send > packet_size){  // 如果剩余的字节数大于packet_size，分块发送
            bytes_to_send = packet_size;
        }
#ifdef YUYV
        int bytes = send(acceptfd, ptVideoDevice->rgb_data[ptVideoDevice->iVideoBufCurIndex] + sent_bytes, bytes_to_send, 0);
#elif defined(MJPEG)
        int bytes = send(acceptfd, ptVideoDevice->pucVideBuf[ptVideoDevice->iVideoBufCurIndex] + sent_bytes, bytes_to_send, 0);
#else
#endif
        if (bytes < 0) {
            if(errno == EPIPE){
                close(acceptfd);
                ptVideoDevice->v4l2_qbuf();
                pthread_exit(NULL);
            }
            Print_RED("发送数据失败, ptVideoDevice->iVideoBufCurIndex = %d",ptVideoDevice->iVideoBufCurIndex);
            break;
        }
        sent_bytes += bytes;
    }
}
